package com.tidc.seaserverweb.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tidc.seaservermapper.dao.UserDao;
import com.tidc.seaservermodel.entity.Fres;
import com.tidc.seaservermodel.util.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @ClassNmae TidcAuthenticationSuccessHandler
 * @Description
 * @Author 14631
 **/
@Component
public class TidcAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Resource
	private ObjectMapper objectMapper;
	@Resource
	private UserDao userDao;
	@Resource
	private RedisUtil redisUtil;
	protected String getCredentialsCharset(HttpServletRequest httpRequest) {
		return "UTF-8";
	}
	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
		com.tidc.seaservermodel.entity.User user = userDao.queryByPhone(authentication.getName());
		UserDetails userDetailsId= new User(user.getId()+"","",true,true,true,true,authentication.getAuthorities());
		// 存入redis，返回key
		String newToken  = UUID.randomUUID().toString();
		//删除旧token 实现踢人
		String oldToken = (String) redisUtil.get(user.getPhone());
		if (oldToken!=null) {
			redisUtil.delete(oldToken);
		}
		//存储userDetail 到redis
		redisUtil.setObject(newToken,userDetailsId);
		redisUtil.set(user.getPhone(),newToken);
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Fres.Success(newToken,"成功")));

	}
}